import 'dart:io';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:package_info_plus/package_info_plus.dart';

class SystemUtils {
  static double getStatusBarHeight(BuildContext context) {
    return MediaQuery.of(context).padding.top;
  }

  static double getScreenWidth(BuildContext context) {
    return MediaQuery.of(context).size.width;
  }

  static double getScreenHeight(BuildContext context) {
    return MediaQuery.of(context).size.height;
  }

  //获取设备ID
  static Future<String> getDeviceId() async {
    String deviceId = "88888888";
    DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
    try {
      if (Platform.isAndroid) {
        AndroidDeviceInfo androidDeviceInfo = await deviceInfoPlugin.androidInfo;
        deviceId = androidDeviceInfo.androidId ?? deviceId;
      } else if (Platform.isIOS) {
        IosDeviceInfo iosDeviceInfo = await deviceInfoPlugin.iosInfo;
        deviceId = iosDeviceInfo.identifierForVendor ?? deviceId;
      }
    } on PlatformException {
      return deviceId;
    }
    return deviceId.toUpperCase();
  }

  static Future<String> getVersionName() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    return packageInfo.version;
  }

  static Future<String> getVersionCode() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    return packageInfo.buildNumber;
  }

  static Future<String> getVersionNameAndCode() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    return packageInfo.version + "(" + packageInfo.buildNumber + ")";
  }

  static Future<String> getPackageName() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    return packageInfo.packageName;
  }

  static Future<PackageInfo> getPackageInfo() async {
    PackageInfo info = await PackageInfo.fromPlatform();
    return info;
  }

  //验证版本号
  static Future<bool> verifyVersion(String? serviceVersion) async {
    if (serviceVersion == null || serviceVersion.isEmpty || !serviceVersion.contains(".")) {
      return false;
    }
    String localVersion = await getVersionName();
    String lv = localVersion.replaceAll(".", "");
    String sv = serviceVersion.replaceAll(".", "");
    if (sv.length > lv.length) {
      sv = sv.substring(0, lv.length);
      return int.parse(sv) >= int.parse(lv);
    } else {
      lv = lv.substring(0, sv.length);
      return int.parse(sv) > int.parse(lv);
    }
  }

  static void closeKeyboard(BuildContext context) {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus!.unfocus();
    }
  }
}
